import type { Song } from '~/types/song'
import songsData from '~/server/data/songs.json'

export default defineEventHandler((event) => {
  const query = getQuery(event)
  const songs: Song[] = songsData

  let songList = [...songs]

  // Search
  if (query.q) {
    const searchTerm = (query.q as string).toLowerCase()
    songList = songList.filter(
      song =>
        song.song_name.toLowerCase().includes(searchTerm) ||
        song.singer.toLowerCase().includes(searchTerm),
    )
  }

  // Filter by styles
  if (query.styles) {
    const styles = (query.styles as string).split(',')
    songList = songList.filter(song =>
      styles.every(style => song.styles.includes(style)),
    )
  }

  // Sort
  if (query.ordering) {
    const field = (query.ordering as string).startsWith('-')
      ? ((query.ordering as string).substring(1) as keyof Song)
      : ((query.ordering as string) as keyof Song)
    const order = (query.ordering as string).startsWith('-') ? 'desc' : 'asc'

    songList.sort((a, b) => {
      const aValue = a[field]
      const bValue = b[field]

      if (aValue < bValue) return order === 'asc' ? -1 : 1
      if (aValue > bValue) return order === 'asc' ? 1 : -1
      return 0
    })
  }

  const total = songList.length
  const page = Number(query.page || 1)
  const limit = Number(query.limit || 10)
  const paginatedSongs = songList.slice((page - 1) * limit, page * limit)

  return {
    results: paginatedSongs,
    total,
  }
})